package com.oa.android.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.FileMangeAdapter;
import com.oa.android.entry.FileM;
import com.oa.android.entry.FileMu;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.XListView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


/**
 * 文件夹下面
 *
 * @author -zouqh
 */
public class FileDirActivity extends Activity implements OnClickListener, XListView.IXListViewListener {

    private ImageView close;
    private TextView title, searchCru,addEmil,newMulu;
    private XListView listView;
    private LinearLayout layout;
    ProgressDialog dialog;
    private List<FileM> emilList;
    private int page = 1;
    private int pageSize = 12;
    private int allPage = 0;
    private FileMangeAdapter adapter;
    private String keyword = "";
    private Dialog Jdialog;
    private String type;
    private String fileType;
    private String dri="";
    private String filetype;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.file_list_activity);
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        searchCru = (TextView) findViewById(R.id.searchCru);
        addEmil= (TextView) findViewById(R.id.ritgh_text);
        newMulu= (TextView) findViewById(R.id.new_file);
        listView = (XListView) findViewById(R.id.listView);
        layout = (LinearLayout) findViewById(R.id.layout);
        fileType=getIntent().getStringExtra("fileType");
        filetype=getIntent().getStringExtra("type");
//        dri=Integer.parseInt(getIntent().getStringExtra("dri"));
        title.setText(fileType);
        layout.setVisibility(View.GONE);

        searchCru.setHint("   搜索文件名称");
        listView.setPullLoadEnable(true);// 向上滑动加载更多开启
        listView.setPullRefreshEnable(false);
        listView.setXListViewListener(this);
        listView.setFooterName("", false);
        close.setOnClickListener(this);
        addEmil.setOnClickListener(this);
        searchCru.setOnClickListener(this);
        newMulu.setOnClickListener(this);
        emilList = new ArrayList<>();

        if (filetype!=null&&(filetype.equals("1")||filetype.equals("0"))){
            fileType="0";
//            addEmil.setVisibility(View.VISIBLE);
            newMulu.setVisibility(View.VISIBLE);
//            listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//                @Override
//                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//
//                    pointDialog("确定删除文件夹吗？",position-1);
//                    return true;
//                }
//            });
        }
        adapter = new FileMangeAdapter(this, emilList);
        listView.setAdapter(adapter);
        getDate();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (emilList.get(position-1).getDFBZ()!=null&&emilList.get(position-1).getDFBZ().equals("1")){
                    Intent intent=new Intent(FileDirActivity.this,FileItemActivity.class);
                    intent.putExtra("name",emilList.get(position-1).getFILENAME());
//                  intent.putExtra("fileType",emilList.get(position-1).getTYPENAME());
                    intent.putExtra("type",filetype);
                    intent.putExtra("dri",emilList.get(position-1).getID());
                    startActivity(intent);
                }

            }
        });
        ItemOnLongClick1();

    }


    private void ItemOnLongClick1() {
//注：setOnCreateContextMenuListener是与下面onContextItemSelected配套使用的
        listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {

            public void onCreateContextMenu(ContextMenu menu, View v,
                                           ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作");
                menu.add(0,0,0,"重命名");
                menu.add(0,1,0,"删除");


            }
        });
    }

    // 长按菜单响应函数
    @Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
//
        int id = (int)info.id;

        System.out.println("id----"+id);

        switch(item.getItemId()) {
            case 0:
                changeName(emilList.get(id).getFILENAME(),emilList.get(id).getID(),id);
            break;

            case 1:
            //
                pointDialog("确定删除文件夹吗？",id);
            break;



            default:
                break;
        }

        return super.onContextItemSelected(item);

    }

    /**
     * 提示
     */
    private void pointDialog(String str, final int p) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        dialogTitle.setText(str);
        sure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
                Jdialog.cancel();
                delectFile(p);


            }
        });
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Jdialog.dismiss();
            }
        });

    }


    /**
     * 修改文件名
     */
    private void changeName(final String name, final String id, final int p) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.rename_layout,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        final EditText input = (EditText) layout.findViewById(R.id.filename);
        TextView sure = (TextView) layout.findViewById(R.id.sure);
        TextView cancel = (TextView) layout.findViewById(R.id.cancel);
        input.setText(name);
        sure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
                if (input.getText().toString().length()>0){
                    Jdialog.cancel();
                    getChange(input.getText().toString(),id,p);
                }else{
                    Toast.makeText(FileDirActivity.this,"请输入名称",Toast.LENGTH_SHORT).show();
                }



            }
        });
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Jdialog.dismiss();
            }
        });

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent intent;
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.searchCru:
                intent = new Intent(this, SearchActivity.class);
                startActivityForResult(intent, 1);
                break;

            case R.id.ritgh_text:
                intent = new Intent(this, UpFFileActivity.class);
                intent.putExtra("df",dri+"");
                startActivityForResult(intent,2);
                break;
            case R.id.new_file:
                intent = new Intent(this, NewFileActivity.class);
                intent.putExtra("df",dri+"");
                intent.putExtra("type",filetype);
                startActivityForResult(intent,2);
//                startActivity(intent);
                break;

            default:
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (page < allPage) {
                        page++;
                        getDate();
                    } else {
                        listView.setFooterName("", false);
                    }
                    break;

            }

        }
    };




    //获取文件夹列表
    private void getDate() {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(UConstants.GET_FILEDIR_LIST);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("LX", filetype);
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", pageSize + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        allPage = Integer.parseInt(object.getString("total"));
                        allPage = (int) Math.ceil((double) allPage / pageSize);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Gson gson = new Gson();
                            Type lt = new TypeToken<List<FileM>>() {
                            }.getType();
                            List<FileM> list = gson.fromJson(object.getString("rows").toString(), lt);
//                            getJson(object.getString("rows").toString());
                            if (list != null && list.size() > 0) {
//								adapter = new CurstorAdapter(OlneSelectActivity.this, crutorJluList);
//								listView.setAdapter(adapter);
                                emilList.addAll(list);
                                adapter.notifyDataSetChanged();
                                if (page == allPage) {
                                    listView.setFooterName("", false);
                                } else if (page <= allPage) {
                                    listView.setFooterVisibility(true);
                                }

                            } else {
                                Toast.makeText(x.app(), "暂无文件！", Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(x.app(), "暂无文件！", Toast.LENGTH_LONG).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }



    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        handler.sendEmptyMessage(1);
        onLoad();


    }

    private void onLoad() {
        listView.stopRefresh();
        listView.stopLoadMore();
        listView.setRefreshTime("刚刚");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    keyword = data.getStringExtra("keyword");
                    emilList.clear();
                    page = 1;
                    adapter.notifyDataSetChanged();
                    getDate();

                }
            }
        }else if (requestCode == 2) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    String str = data.getStringExtra("success");
                    if (str!=null&&str.equals("1")){
                        emilList.clear();
                        page = 1;
                        adapter.notifyDataSetChanged();
                        getDate();
                    }


                }
            }
        }

    }

    //删除个人文
    private void delectFile(final int positon) {
        dialog = ProgressDialog.show(this, null, "删除中...", true, false);
        RequestParams params = new RequestParams(UConstants.DELETE_FILE);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("ID", emilList.get(positon).getID());
        params.addBodyParameter("LX", filetype);

        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);

                        boolean success = object.getBoolean("success");
//
                        if (success) {
                            emilList.remove(positon);
                            adapter.notifyDataSetChanged();
                            Toast.makeText(x.app(), "删除成功！", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(x.app(), "删除失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "删除出错！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    //修改文件名
    private void getChange(final String name, String id, final int positon) {
        dialog = ProgressDialog.show(this, null, "修改中...", true, false);
        RequestParams params = new RequestParams(UConstants.EDTI_FILENAME);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("ID", id);
        params.addBodyParameter("FILENAME", name);

        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);

                        boolean success = object.getBoolean("success");
//
                        if (success) {
                            emilList.get(positon).setFILENAME(name);
                            adapter.notifyDataSetChanged();
                            Toast.makeText(x.app(), "修改成功！", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(x.app(), "修改失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "修改出错！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }
}
